package com.xyh.controller;

import com.xyh.config.ApplicationConfig;
import com.xyh.po.User;
import com.xyh.service.UserService;
import com.xyh.service.impl.UserServiceImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author:kyle
 * @Date:2020/12/15 - 17:04
 * @Project:spring_demo1
 * @Package:${PACKAGE_NAME}
 * @Version:1.0
 */
@WebServlet(name = "UserServlet",urlPatterns = "/user.do")
public class UserServlet extends HttpServlet {

    private UserServiceImpl userService;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> list = userService.list();
        request.setAttribute("users",list);
//        请求转发，服务器端跳转
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    @Override
    public void init() throws ServletException {
        //这种写法每次都要去读取配置文件和创建对象。不可取
//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        userService = context.getBean("userService", UserServiceImpl.class);
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        userService = webApplicationContext.getBean("userService", UserServiceImpl.class);

    }
}
